#include <func.h>

#define PORT "10086"

int main(int argc, char* argv[])
{
    // ./daytime_client host
    if (argc != 2) {
        error(1, 0, "Usage: %s host", argv[0]);
    }

    // 1. 获取服务器的地址
    struct addrinfo hints;
    bzero(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;

    struct addrinfo *result, *p;
    int err = getaddrinfo(argv[1], PORT, &hints, &result);
    if (err) {
        fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(err));
        exit(1);
    }

    // 遍历地址，发送数据报
    int sockfd;
    for (p = result; p != NULL; p = p->ai_next) {
        // 创建主动套接字
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            continue;
        }
        // 发送数据报
        if (sendto(sockfd, "", 0, 0, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            continue;
        }
        // 发送成功, 接收日期和时间
        // 格式: YYYY-MM-DD HH:mm:ss 
        char daytime[20];
        if (recvfrom(sockfd, daytime, 20, 0, NULL, NULL) != -1) {
            puts(daytime);
            close(sockfd);
            break;
        }
    }

    // 释放地址信息
    freeaddrinfo(result);

    return 0;
}

